rm(list = ls())

##Setting the working directory: be careful not to overwrite existing graphs
setwd("C:/Users/patri/Dropbox/My Projects/Spring 2021/Empirical IR/Data")

library(mediation)
library(haven)


set.seed(031122)

HRdata <- read_dta("threatHR_2.dta")
#Only include data after 1979
HRdata2<-subset(HRdata, year>1979)
HRdata3<-subset(HRdata2, oced!=1)

library(plm)
#Country fixed effects and year fixed effects
##Focus on threat and v2stfisccap2 (State Capacity)
yp <- plm(theta_mean2  ~ threat+ v2stfisccap3 +  v2x_polyarchy + max_civilwar2 
          +lnpop+ lngdp_pc
          , model = "within", effect = "twoways" ,data=HRdata3)
summary(yp)

#Same model, but using the lm command (inputting fixed effects `by hand`)
#The mediate package doesn't work with the plm command
y <- lm(fwi_theta_mean2 ~ wi_v2stfisccap3 + wi_threat +  wi_v2x_polyarchy + max_civilwar2 
        +wi_lnpop+ wi_lngdp_pc, data=HRdata3)
##Check results to see if they're the same
#library(faraway)
#sumary(y)

esample.n <- nobs(y)
esample<-rownames(as.matrix(resid(y)))
##Equation 1 and 2 of mediation will need to have the same number of observations, so I'm subsetting the data. 
HRdata4<-HRdata3[esample,]

##Equation #1 - Mediator
m<- lm(wi_v2stfisccap3 ~ wi_threat +  wi_v2x_polyarchy + max_civilwar2 
       +wi_lnpop+ wi_lngdp_pc, data=HRdata4)
summary(m)

##Equation #2 - Outcome
y <- lm(fwi_theta_mean2 ~ wi_v2stfisccap3 + wi_threat +  wi_v2x_polyarchy + max_civilwar2 
        +wi_lnpop+ wi_lngdp_pc, data=HRdata4)
summary(y)

  #Without bootstrapping 
  
 m.out<-mediate(m, y, treat = "wi_threat",
                 mediator = "wi_v2stfisccap3")
 ##mediate will take a minute or so to run
 
 ##Summarize mediation effects
 summary(m.out)
 plot(m.out, xlim=c(-0.1,0.5), xlab="Estimated Effect")
      
      
  
 #ACME - Indirect (negative), ADE - Direct Effect (positive)
 #What's this mean? Threat has a negative indirect effect on  repression because of threat
 #increases capacity. But threat increases repression because leaders use threats as an 
 #excuse to repress opposition
 
 #With bootstrapping (occassional error, not sure why, but result same as above)
 m.out2<-mediate(m, y, boot=TRUE, sims=1000, treat = "wi_threat",
                 mediator = "wi_v2stfisccap3")
 summary(m.out2)

